<!--加积分-->
<template>
  <section>
  </section>
</template>

<script>
  /**
   * 定时添加上传缓存中的阅读数据
   * 为了防止接口慢导致的数据没有提交成功的问题
   * 默认记录加积分，用时间戳作KEY记录所有加分操作，用status为1表示正在提交，
   *
   */
  /*
   let data = {
   key: '',
   status: 1,
   methodName: '', // 接口名称
   params: {} // 请求参数
   }
   */
  /*type: 1:是新闻，2：音视频*/
  import readScore from '@/utils/readScore'
  export default {
    name: 'commentComponent',
    props: ['_contentId', 'type'],
    data () {
      return {
        contentId: '',
        trueReadTimer: '',
        readTimer: ''
      }
    },
    created () {
      console.log('start read news')
      this.startRead()
    },
    beforeDestroy () {
      this.stopRead()
    },
    methods: {
      startRead () {
        console.log('readscore startRead', this._contentId)
        let trueReadTime = 30
        let readTime = this.type === 1 ? 180 : 180
        this.stopRead()
        // 有效阅读
        this.readTimer = setInterval(() => {
          if (this.type === 1) {
            this.getScore('read')
          }
        }, trueReadTime * 1000)
        // 阅读时长
        this.trueReadTimer = setInterval(() => {
//          this.getScore(this.type === 1 ? 'readTrue' : 'watchTrue')
          let me = this
          readScore.addTime(this.type, (function () {
              return function () {
                me.getScore(me.type === 1 ? 'readTrue' : 'watchTrue')
              }
            })()
          )
        }, 1000)
      },
      stopRead () {
        clearInterval(this.trueReadTimer)
        clearInterval(this.readTimer)
      },
      getScore (type) {
        let methods = {
          read: 'getcontentRead',   // 有效阅读
          readTrue: 'getstudyTime',   // 阅读时长
          watchTrue: 'getwatchVideoTime',   // 视听时长
          watch: 'getwatchVideo'   // 有效视听
        }
        let params = {
          businessId: this._contentId,
          userId: this.tools.getUserInfo().id
        }
        let key = Date.now()
        if (!params.userId || !params.businessId) {
          return false
        }
        this.tools.readScore.add(
          {
            key,
            status: 1,
            methodName: methods[type], // 接口名称
            params // 请求参数
          }
        )
        this.fetchService[methods[type]](params).then(res => {
          if (res.code === 0) {
            this.tools.readScore.remove(key)
            return
//            return this.tools.tip(res.message)
          }
          console.log(type)
          if (type.indexOf('True') >= 0) { // 阅读时长
            clearInterval(this.trueReadTimer)
          } else { // 有效阅读
            clearInterval(this.readTimer)
          }
        })
      }
    }
  }
</script>

<style scoped lang="scss">
</style>
